package com.ai.smlcore.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class TxtUtil {
	public static boolean isMobileNumber(String mobiles) {
		return Pattern.compile("^1\\d{10}").matcher(mobiles).matches();
	}
	
	/**
	 * 设置模板错误信息
	 * 
	 * @param num
	 * @param fileName
	 * @param linked
	 * @author yangyanli
	 */
	public void setErrorInfo(int num,String fileName,Map<String, String> linked){
		linked.clear();
		linked.put("flag", "false");
		linked.put("row", num+"");
		linked.put("FILE_NM", fileName);
		linked.put("ERROR_RSN_DESC", (num + 1) + "模版错误");
		linked.put("ERROR_DESC", "目标客户模版不正确");
	}
		
	public List<Map<String, String>> readTxt(InputStream inputStream, String fileName) throws IOException {

		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
		String lineTxt = null;
		List<Map<String, String>> list = new LinkedList<Map<String, String>>();
		List<String> tableHead = new ArrayList<String>();//存放内容、个数都不确定的表头信息
		// 定义一个行号 初始化为0
		int num = 0;
		while ((lineTxt = bufferedReader.readLine()) != null) {
			num = num + 1;//txt文件行号从1开始
			if(lineTxt.length()==0){//如果内容中有一行为空，隔过去执行下一行
				continue;
			}
			Map<String, String> linked = new HashMap<String, String>();
			// 行号小于等于8就跳出单词循环
			if (num <= 8) {
				if(!lineTxt.startsWith("***") || !lineTxt.endsWith("***")){
					setErrorInfo(num,fileName,linked);
					break;
				}
								
				if(num == 5){
					//获取第5行设定的表头信息,表头信息写在模板的两个冒号之间，各个信息之间用竖线分割开
					int colon1st = lineTxt.indexOf(":");
					int colon2ed = lineTxt.lastIndexOf(":");
					int vertical = lineTxt.indexOf("|");
					if((colon1st != -1) && (colon2ed != -1) && (colon1st != colon2ed)){//第5行，并且两个冒号中间有内容
						String lineTxtSub = lineTxt.substring(colon1st + 1,  colon2ed);
						if(vertical != -1){
							tableHead = Arrays.asList(lineTxtSub.split("\\|",-1));//数组转换为List（不可增删）
						}else{//没有分割标识
							tableHead = Arrays.asList(lineTxtSub);
						}
						System.out.println("表头：" + lineTxt.substring(colon1st + 1,  colon2ed));
						if(tableHead.get(0).length() == 0 && !tableHead.get(0).contains("号码")){//??是否需要判断第一个字段非空并且包含有"号码"两个字
							setErrorInfo(num,fileName,linked);
							list.add(linked);
							break;
						}
					}else {
						setErrorInfo(num,fileName,linked);
						break;
					}
				}
				
				continue;
			}

			String[] s = lineTxt.split("\\|",-1);
			
			//System.out.println("tableHead.size()=" + tableHead.size() + ",s.length=" + s.length);
			if(s.length == tableHead.size()){//所填数据的个数和表头个数一致
				
				if(!isMobileNumber(s[0].toString())){
					linked.clear();
					linked.put("flag", "false");
					linked.put("row", (num-8)+"");
					linked.put("FILE_NM", fileName);
					linked.put("ERROR_RSN_DESC", (num + 1) + "行,手机格式错误");
					linked.put("ERROR_DESC", "手机格式错误");
					break;
				}else{
					linked.put("flag", "true");
					linked.put("RESV_MOBNUM", s[0].trim());
					linked.put("LIN_CUST_NM", "");
					
					StringBuilder custExtdData = new StringBuilder();//用于保存所有的附属信息，（key1：value1；key2：value2...）
					
					for(int i = 1;i < tableHead.size() - 1;i++){//不需要保存用户号码
						s[i] = ("".equals(s[i].trim())?"null":s[i].trim());//如果该字段是空，那么转存null
						custExtdData.append(tableHead.get(i) + ":" + s[i].trim() + ",");
						//System.out.println("输出为：" + tableHead.get(i) + ":" + s[i].trim());
					}
					s[tableHead.size() - 1] = ("".equals(s[tableHead.size() - 1].trim())?"null":s[tableHead.size() - 1].trim());//如果该字段是空，那么转存null
					custExtdData.append(tableHead.get(tableHead.size() - 1) + ":" + s[tableHead.size() - 1].trim());
					linked.put("CUST_EXTD_DATA", custExtdData.toString());
					list.add(linked);
				}
			}else{
				linked.put("flag", "false");
				linked.put("row", (num-8)+"");
				linked.put("FILE_NM", fileName);
				linked.put("ERROR_RSN_DESC", (num + 1) + "模版错误");
				linked.put("ERROR_DESC", "手机号不能为空,且每一行只能有一个用户信息;数据格式和模板不同");
			}
			
		}
		return list;
	}
}